package speed2010.andreza.vspeed.util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

/**
 * @author <a href="mailto:andreza.lba@gmail.com">Andreza Leite de Alencar</a>
 */
public class SwingUtils {

	static {
		setLookAndFeel();
	}

	public static void setLookAndFeel() {
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch (final Exception e) {
			JFrame.setDefaultLookAndFeelDecorated(true);
			JDialog.setDefaultLookAndFeelDecorated(true);
		}
	}

	public static boolean confirmacao(final java.awt.Component componente, final String mensagem) {
		boolean confirmacao = false;

		if (javax.swing.JOptionPane.showOptionDialog(componente, mensagem, "Confirmation",
				javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.INFORMATION_MESSAGE, null, new String[]{
						"    Yes    ", "    No    "}, "    Yes    ") == javax.swing.JOptionPane.YES_OPTION) {
			confirmacao = true;
		}

		return confirmacao;
	}

	public static File fileDialog(final Component pParent, final int pTipo, final String pDiretorioInicial,
			final String pExtensao) {
		final JFileChooser jf = new JFileChooser(pDiretorioInicial);
		jf.setDialogType(pTipo);
		final String vPontoExtensao = pExtensao == null ? null : "." + pExtensao.toLowerCase();
		if (vPontoExtensao != null) {
			jf.setFileFilter(new FileFilter() {

				@Override
				public String getDescription() {
					return "*" + vPontoExtensao;
				}

				@Override
				public boolean accept(final File pF) {
					return (pF.isDirectory() || pF.getName().toLowerCase().endsWith(vPontoExtensao));
				}
			});
		}
		File vSelectedFile = null;
		if (jf.showDialog(null, null) == JFileChooser.APPROVE_OPTION) {
			vSelectedFile = jf.getSelectedFile();
			if ((vPontoExtensao != null) && !vSelectedFile.getName().toLowerCase().endsWith(vPontoExtensao)) {
				vSelectedFile = null;
			}
		}
		return vSelectedFile;
	}

	public static String inputMessage(final java.awt.Component componente, final String mensagem, final String titulo) {
		return javax.swing.JOptionPane.showInputDialog(componente, mensagem, titulo, JOptionPane.QUESTION_MESSAGE);
	}

	public static void errorMessage(final java.awt.Component componente, final String mensagem, final String titulo) {
		JOptionPane.showMessageDialog(componente, mensagem, titulo, JOptionPane.ERROR_MESSAGE);
	}

	public static void warnMessage(final java.awt.Component componente, final String mensagem, final String titulo) {
		JOptionPane.showMessageDialog(componente, mensagem, titulo, JOptionPane.WARNING_MESSAGE);
	}

	public static void infoMessage(final java.awt.Component componente, final String mensagem, final String titulo) {
		JOptionPane.showMessageDialog(componente, mensagem, titulo, JOptionPane.INFORMATION_MESSAGE);
	}

	public static java.awt.Dimension getDimensaoTela() {
		final java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		final java.awt.Insets screenInsets = java.awt.Toolkit.getDefaultToolkit().getScreenInsets(
				java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
						.getDefaultConfiguration());
		screenSize.height -= screenInsets.bottom;

		return screenSize;
	}

	public static void ajustarColunas(final JTable table) {
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		for (int c = 0; c < table.getColumnCount(); c++) {
			packColumn(table, c, 2);
		}
	}

	private static void packColumn(final JTable table, final int vColIndex, final int margin) {
		final DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
		final TableColumn col = colModel.getColumn(vColIndex);
		int width = 0;

		// Get width of column header
		TableCellRenderer renderer = col.getHeaderRenderer();
		if (renderer == null) {
			renderer = table.getTableHeader().getDefaultRenderer();
		}
		Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);
		width = comp.getPreferredSize().width;

		// Get maximum width of column data
		for (int r = 0; r < table.getRowCount(); r++) {
			renderer = table.getCellRenderer(r, vColIndex);
			comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false, r,
					vColIndex);
			width = Math.max(width, comp.getPreferredSize().width);
		}

		// Add margin
		width += 2 * margin;

		// Set the width
		col.setPreferredWidth(width);
	}

	public static void saveComponentAsPNG(final Component myComponent, final String filename) throws IOException {
		final Dimension size = myComponent.getSize();
		final BufferedImage myImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
		final Graphics2D g2 = myImage.createGraphics();
		myComponent.paint(g2);
		ImageIO.write(myImage, "PNG", new File(filename));
	}

	public static void showSplash(final String pFilename, final Color pBackgroundColor, final long pTime) {
		try {
			JFrame jf = new JFrame();
			jf.setUndecorated(true);
			jf.setBackground(pBackgroundColor);
			final JPanel vContentPane = new JPanel();
			vContentPane.setOpaque(false);
			final JLabel vComp = new JLabel();
			vComp.setIcon(new ImageIcon(ClassLoader.getSystemResource(pFilename)));
			vComp.setOpaque(true);
			vContentPane.add(vComp);
			jf.setContentPane(vContentPane);
			jf.pack();
			jf.setLocationRelativeTo(null);
			jf.setVisible(true);
			Thread.sleep(pTime);
			jf.setVisible(false);
			jf.dispose();
			jf = null;
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	public static void shake(final Component jframe) {
		try {
			final int originalX = jframe.getLocation().x;
			final int originalY = jframe.getLocation().y;
			final long sleepTime = 30;

			for (int i = 0; i <= 2; i++) {
				jframe.setLocation(originalX + 5, originalY);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX + 5, originalY + 5);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX, originalY + 5);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX, originalY);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX - 5, originalY);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX - 5, originalY - 5);
				Thread.sleep(sleepTime);
				jframe.setLocation(originalX, originalY - 5);
				Thread.sleep(sleepTime);
			}

			jframe.setLocation(originalX, originalY);

		} catch (final Exception ex) {
			System.out.println(ex.toString());
		}
	}
}
